<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <title>小疯子博客系统</title>

    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="/adminlte/plugins/fontawesome-free/css/all.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="/adminlte/dist/css/adminlte.min.css">
    <!-- Google Font: Source Sans Pro -->
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
    <link rel="stylesheet" href="/bootstrap-table/bootstrap-table.css">
    <link rel="stylesheet" href="/css/bootstrapStyle/bootstrapStyle.css">

    <!-- jQuery -->
    <script src="/adminlte/plugins/jquery/jquery.min.js"></script>
    <!-- alert -->
    <script src="/js/alert.js"></script>
    <!-- Bootstrap 4 -->
    <script src="/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- AdminLTE App -->
    <script src="/adminlte/dist/js/adminlte.min.js"></script>
    <script src="/bootstrap-table/bootstrap-table.js"></script>
    <script src="/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
    <!-- ztree -->
    <script src="/js/ztree/jquery.ztree.core.js"></script>
    <script src="/js/ztree/jquery.ztree.excheck.js"></script>
    <script src="/js/ztree/jquery.ztree.exedit.js"></script>
    <style>
        .ztree li a{
            color: #FFF;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <div id="updateDiv" style="display: none">
        <input id="alert" type="button" value="Alert" />
        <input id="confirm" type="button" value="Confirm" />
    </div>
    <!-- head view -->
    <#include "/common/head.ftl" />
    <!-- left view -->
    <#include "/common/left.ftl" />

    <!-- 模态框（Modal） -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel"></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <form id="rolefm">
                        <div class="form-inline">
                            <input type="text" name="id" id="id" hidden>
                            <label class="col-sm-2" for="roleName">角色名称</label>
                            <input type="text" class="form-control col-sm-4" name="roleName" id="roleName" placeholder="请输入角色名称" />
                            <label class="col-sm-2" for="requireRole">权限代码</label>
                            <input type="text" class="form-control col-sm-4" name="requireRole" id="requireRole" placeholder="请输入权限代码" />
                        </div>
                        <div class="form-inline" style="margin-top:5px">
                            <label class="col-sm-2" for="descript">描述</label>
                            <textarea class="form-control col-sm-10" rows="4" name="descript" id="descript"></textarea>
                        </div>
                        <div class="form-group" style="margin-top:5px;">
                            <label class="col-sm-2">权限</label>
                            <ul style="height:500px;overflow-y: scroll; background-color: #000; color: #fff" id="treeDemo" class="ztree"></ul>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="roleSubmit" type="button" class="btn btn-primary">提交更改</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    <!-- /.modal -->

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 text-dark">角色管理</h1>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12">
                        <div id="toolbar" class="btn-group">
                            <button id="btn_insert" type="button" class="btn btn-default">
                                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>新增
                            </button>
                        </div>
                        <table id="table" style="background-color: ActiveBorder"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Main Footer -->
    <#include "/common/foot.ftl" />
</div>
</body>
<script>

    <!-- 初始化ztree -->
    var setting = {
        view: {
            selectedMulti: false
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };

    $(document).ready(function(){
        initMainTable();
    });


    let $table;
    //初始化加载table
    function initMainTable() {
        $table = $('#table').bootstrapTable({
            url: "/user/role/list",         //请求后台的URL（*）
            method: "GET",                      //请求方式（*）
            toolbar: "#toolbar",
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "desc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
            pageSize: 10,                     //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                      //是否显示表格搜索
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列（选择显示的列）
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            //height: 500,                      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                   //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                  //是否显示父子表
            //得到查询的参数
            queryParams: function (params) {
                //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                };
                return temp;
            },
            columns: [
                {
                    field: 'roleName',
                    title: '角色名',
                    sortable: false,
                    align: 'center',
                    width: 300
                }, {
                    field: 'requireRole',
                    title: '权限值',
                    sortable: false,
                    align: 'center',
                    width: 150
                }, {
                    field: 'createTime',
                    title: '创建时间',
                    sortable: false,
                    align: 'center',
                    width: 200
                }, {
                    title: '操作',
                    align: 'center',
                    formatter:function(value,row,index){
                        let e = '<button style="margin-right:5px" type="button" class="btn btn-primary" onclick="updateFun(\''+ row.id +'\')">修改</button>';
                        let d = '<button type="button" class="btn btn-danger" onclick="deleteFun(\''+ row.id +'\')">删除</button>';
                        return e+d;
                    }
                }
            ],
            responseHandler: function (result) {
                if(result.status==1){
                    return {
                        "total": result.data.total,
                        "rows": result.data.records
                    };
                }
            },
            onLoadSuccess: function (data) {
            },
            onLoadError: function () {
            },
            onDblClickRow: function (row, $element) {
                // var id = row.ID;
                // EditViewById(id, 'view');
            }
        })
    }

    //删除角色
    function deleteFun(id){
        myConfirm("确认！", "确定要删除这个角色么？", function(r) {
            if (r) {
                $.ajax({
                    type: "post",
                    url: "/user/role/delete",
                    data: {
                        "id": id
                    },
                    success: function (data) {
                        if (data.status === 1) {
                            myAlert("提示", "删除成功", function(){
                                $("#table").bootstrapTable("refresh");
                            })
                        } else {
                            myAlert("操作失败", data.message, function(){
                                $("#table").bootstrapTable("refresh");
                            })
                        }
                    }
                })
            }
        })
    }

    //编辑角色
    function updateFun(id) {
        $.ajax({
            type: "get",
            url: "/user/role/all",
            data: {roleId: id},
            success: function(result){
                if (result.status === 1) {
                    $("#id").val(result.extendData.id);
                    $("#roleName").val(result.extendData.roleName);
                    $("#requireRole").val(result.extendData.requireRole);
                    $("#descript").val(result.extendData.descript);
                    $.fn.zTree.init($("#treeDemo"), setting, result.data);
                    $('#myModal').modal('show');
                } else {
                    myAlert("操作失败", result.message);
                }
            }
        })
    }

    //新增点击
    $("#btn_insert").bind("click",function() {
        $.ajax({
            type: "get",
            url: "/user/role/all",
            success: function(result){
                if (result.status === 1) {
                    $.fn.zTree.init($("#treeDemo"), setting, result.data);
                    $('#myModal').modal('show');
                } else {
                    myAlert("操作失败", result.message);
                }
            }
        })
    })

    //提交更新
    $("#roleSubmit").bind("click", function(){
        let roleName = $("#roleName").val();
        if(typeof(roleName) == undefined || roleName==null || roleName==""){
            myAlert("提示", "角色名称不能为空");
            return;
        }
        let requireRole = $("#requireRole").val();
        if(typeof(requireRole) == undefined || requireRole==null || requireRole==""){
            myAlert("提示", "权限代码不能为空");
            return;
        }
        let descript = $("#descript").val();
        let id = $("#id").val();
        let tree = $.fn.zTree.getZTreeObj("treeDemo");
        let auths = new Array();
        tree.getCheckedNodes().forEach(function(item){
            auths.push(item.id);
        })
        $.ajax({
            type: "post",
            url: "/user/role/add",
            data: {
                id: id,
                roleName: roleName,
                requireRole: requireRole,
                descript: descript,
                auths: auths
            },
            success: function(result){
                if (result.status === 1) {
                    myAlert("提示", "提交成功", function(){
                        $('#myModal').modal('hide');
                        $("#table").bootstrapTable("refresh");
                    });
                } else {
                    myAlert("操作失败", result.message);
                }
            }
        })
    })
</script>
</html>
